package com.dt.record

import android.Manifest
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
class MainActivity : AppCompatActivity() {

    private lateinit var vWin:VideoControl

    private val mHideHandler = Handler()
    private val mHidePart2Runnable = Runnable {
        // Delayed removal of status and navigation bar

        // Note that some of these constants are new as of API 16 (Jelly Bean)
        // and API 19 (KitKat). It is safe to use them, as they are inlined
        // at compile-time and do nothing on earlier devices.
        /*bg_view.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LOW_PROFILE or
                        View.SYSTEM_UI_FLAG_FULLSCREEN or
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN*/

                /*View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
                *//*View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR or
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or*//*
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY*/
    }
    private val mShowPart2Runnable = Runnable {
        // Delayed display of UI elements
//        supportActionBar?.show()
        if(button_full.tooltipText == "window")
            fullscreen_content_controls.visibility = View.VISIBLE

        seekView.visibility = View.VISIBLE

    }
    private var mVisible: Boolean = false
    private val mHideRunnable = Runnable {
        hide()
        seekView.visibility = View.VISIBLE
        mVisible = true
    }

    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private val mDelayHideTouchListener = View.OnTouchListener { _, _ ->
        if (AUTO_HIDE) {
            delayedHide(AUTO_HIDE_DELAY_MILLIS)
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        /*设置沉浸式主题*/
        if (Build.VERSION.SDK_INT >= 21) {

            var decorView = getWindow().getDecorView()
            var option = (View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
                    View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN )

            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT)
        }

        requestPermission()

//        FileManage(this)

         vWin=VideoControl(mVideoView, this)
         vWin.setVideoFile("/Scenery.mp4")

        mVisible = true

        // Set up the user interaction to manually show or hide the system UI.
//        bg_view.setOnClickListener { toggle() }

        // Upon interacting with UI controls, delay any scheduled hide()
        // operations to prevent the jarring behavior of controls going away
        // while interacting with the UI.
//        button_shrink.setOnTouchListener(mDelayHideTouchListener)

    }



    private fun requestPermission() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) { //表示未授权时
            //进行授权
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                1
            )
        } else {
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //同意权限申请
            } else { //拒绝权限申请
                Toast.makeText(this, "权限被拒绝了", Toast.LENGTH_SHORT).show()
            }
            else -> {
            }
        }
    }


    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(50)
    }

     fun toggle() {
        if (mVisible) {
            hide()
        } else {
            show()
        }
    }

    private fun hide() {
        // Hide UI first
        supportActionBar?.hide()
        fullscreen_content_controls.visibility = View.GONE
        seekView.visibility = View.GONE
        mVisible = false

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable)
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY.toLong())
    }

    private fun show() {
        // Show the system bar
        /*bg_view.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION*/
        mVisible = true


        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable)
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY.toLong())
    }

    /**
     * Schedules a call to hide() in [delayMillis], canceling any
     * previously scheduled calls.
     */
    private fun delayedHide(delayMillis: Int) {
        mHideHandler.removeCallbacks(mHideRunnable)
        mHideHandler.postDelayed(mHideRunnable, delayMillis.toLong())
    }



    companion object {
        /**
         * Whether or not the system UI should be auto-hidden after
         * [AUTO_HIDE_DELAY_MILLIS] milliseconds.
         */
        private val AUTO_HIDE = true

        /**
         * If [AUTO_HIDE] is set, the number of milliseconds to wait after
         * user interaction before hiding the system UI.
         */
        private val AUTO_HIDE_DELAY_MILLIS = 3000

        /**
         * Some older devices needs a small delay between UI widget updates
         * and a change of the status and navigation bar.
         */
        private val UI_ANIMATION_DELAY = 300
    }

    fun startOnClick(view: View){
        if (button_play.tooltipText == "start") {
            button_play.tooltipText = "pause"

            vWin.start()

        }else{
            button_play.tooltipText = "start"

            vWin.pause()

        }
//        view.tooltipText
        Log.i("videoWin-----", button_play.tooltipText.toString())
    }

    fun stopOnClick(view: View){

        button_play.tooltipText = "start"

        vWin.stop()

    }

    fun fullScreamOnClick(view: View){
        vWin.fullScream()
    }

    fun gettime(view: View){
        Log.i(
            "now time",
            mVideoView.currentPosition.toString() + "," + mVideoView.duration.toString()
        )
//        mVideoView.set
    }

    fun openFileBrowser(view: View) {

        val intent = Intent(this, FileBrowserActivity::class.java)

        intent.putExtra("area", true)
        startActivityForResult(
            intent,
            1
        )
    }
    fun returnFileBrowser(msg: String){
        Log.i("main_return", msg)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (1 == requestCode) {
            var bundle: Bundle? = null
            if (data != null && data.extras.also { bundle = it } != null) {
                val path = bundle!!.getString("file")
                Log.d(MainActivity::class.java.simpleName + "--->", "onActivityResult: $path")
                //path就是对应的路径信息
//                changePath.setText("选择路径为 : $path")
            }
        }
    }

}

class DatabaseOpenHelper  /*实现构造方法，每个类必须有的，参数就是上面定义好的，直接用。*/
    (context: Context?) : SQLiteOpenHelper(context, DATA_BASE_NAME, null, DATA_BASE_VERSION) {
    /*sql语句，用来创建表，此处创建了四个键，其中_id为主键，主键与表项一一对应，不可重复。*/
    private val CREATE_CAST_TABLE =
        "create table " + TABLE_NAME + "(_id integer primary key autoincrement, name text,age integer,sex text)"

    override fun onCreate(db: SQLiteDatabase) {
        //用已经写好的语句来创建表
        db.execSQL(CREATE_CAST_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {}

    companion object {
        private const val DATA_BASE_NAME = "movie.db" //创一个叫建movie.db的数据库
        const val TABLE_NAME = "casttable" //这是即将创建的表的名称
        private const val DATA_BASE_VERSION = 1 //这个值最低为1，用来让计算机识别匹配数据库
    }



}

class provider : ContentProvider() {
    private var sqLiteDatabase: SQLiteDatabase? = null
    override fun onCreate(): Boolean {
//        TODO("Not yet implemented")
        //因为要使用SQLiteDatabase的query功能，所以创建时不使用DatabaseOpenHelper，而使用其父类SQLiteDatabase。
        sqLiteDatabase = DatabaseOpenHelper(context).getWritableDatabase()
        //用父类创建变量，用子类来实现变量，这叫做对象的多态，向上转型。
//        sqLiteDatabase.beginTransaction() //数据库开始工作

        val contentValues = ContentValues() //新建一个表项

        //给表项的key添加值，注意id是自从生成的，不用我们手动添加，否则报错。

        //将我们创建的表项插入表中
//        sqLiteDatabase.insert(DatabaseOpenHelper.TABLE_NAME, null, contentValues)
        //清空表项，装入新值。
//        sqLiteDatabase.insert(DatabaseOpenHelper.TABLE_NAME, null, contentValues)
        //数据库创建完成
//        sqLiteDatabase.setTransactionSuccessful()
//        sqLiteDatabase.endTransaction()


        return false
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
//        TODO("Not yet implemented")
        val name = "name"
        if(uri == null){
            throw  IllegalArgumentException("Unsupported URI:" + uri)
        }
        return sqLiteDatabase?.query(
            name,
            projection,
            selection,
            selectionArgs,
            null,
            null,
            sortOrder,
            null
        );

    }

    override fun getType(uri: Uri): String? {
//        TODO("Not yet implemented")
        return null
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
//        TODO("Not yet implemented")
        return null
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
//        TODO("Not yet implemented")
        return 0
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
//        TODO("Not yet implemented")
       return 0
    }


}




/**
 * MediaPlayer的播放器控件
  https://www.jianshu.com/p/80dc3d61bfc2
 *
  https://blog.csdn.net/jun5753/article/details/81222448
  https://www.jianshu.com/p/c5d972ab0309
 *
 * 需要搭建双页面,此页面为播放器页面,差一个主页面(文件管理器)
 *
 * 新方法 https://blog.csdn.net/zxd1435513775/article/details/81507909
  https://blog.csdn.net/suyimin2010/article/details/91125841
 *
  https://www.cnblogs.com/guanxinjing/p/11177739.html
  https://blog.csdn.net/liujigangisgood/article/details/40044709 //路径获取
  https://www.cnblogs.com/laijinquan/p/5947832.html //全屏
  http://www.fhdq.net/

 * 有异常,了解一下如何使用Content Provider来调用应用目录外的文件
 *
 * 除了视频还会出现图片,先看看视频播放器能不能显示图片,不行就调用外部软件
 *
 * netTool那边在改跳转到权限页面,看看sublimeText的记录
 *
 * 画面放大缩小 /缺放大后移动
 *
 * 把文件放到app文件目录,试试会不会报错,先把界面画好回头再调试这个
 *
 *
  https://bbs.csdn.net/topics/394527420
 *
  https://blog.csdn.net/googleoyyp/article/details/54956408
 *
 *
  https://www.pocketdigi.com/20110715/394.html
  https://blog.csdn.net/deng0zhaotai/article/details/12446077
  https://www.jianshu.com/p/0aa4a162b024
  https://blog.csdn.net/qq_15059163/article/details/79242329
  https://www.cnblogs.com/linjiqin/archive/2011/05/28/2061396.html


    实现了基本的界面
    video
    缺少页面放大按钮,放大页面拖动区域显示,双击暂停,
    读取错误
    格式兼容

    fileBrowser
    下一个界面是文件浏览器框放大
    需要知道如何点击字体

https://cloud.tencent.com/developer/article/1361737
https://blog.csdn.net/weixin_37716758/article/details/90083310


搜到两个gradle-wrapper.properties,里面都有版本,升级gradle后报错是其中一个版本没改过来
zhanghj@DevStation:^android_app$
zhanghj@DevStation:^android_app$ag -r 2.14.1 FileBrowser/
FileBrowser/app/gradle/wrapper/gradle-wrapper.properties
6:distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

FileBrowser/gradle/wrapper/gradle-wrapper.properties
6:distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip


 尝试不要跳转页面,直接在本页面做文件列表框,把videoView隐藏就可以了,删除,重命名,新建目录按键要动态显示 //不可行

参考做文件管理页面的长按工具栏
https://blog.csdn.net/lk_blog/article/details/7537200

接下来做长按显示勾和选项栏
https://www.cnblogs.com/ll564345575/p/3930294.html

 checkbox图标尺寸问题 OK

 无法使用应该是kotlin不支持的原因


 * */